package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.app.domain.AppImGroupJoinLog;
import com.ruoyi.app.domain.bo.AppImGroupJoinLogBo;
import com.ruoyi.app.domain.vo.AppImGroupJoinLogVo;
import com.ruoyi.app.mapper.AppImGroupJoinLogMapper;
import com.ruoyi.app.service.IAppImGroupJoinLogService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 群组进退记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-13
 */
@RequiredArgsConstructor
@Service
public class AppImGroupJoinLogServiceImpl implements IAppImGroupJoinLogService {

    private final AppImGroupJoinLogMapper baseMapper;

    /**
     * 查询群组进退记录
     */
    @Override
    public AppImGroupJoinLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询群组进退记录列表
     */
    @Override
    public TableDataInfo<AppImGroupJoinLogVo> queryPageList(AppImGroupJoinLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppImGroupJoinLog> lqw = buildQueryWrapper(bo);
        Page<AppImGroupJoinLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollUtil.isNotEmpty(result.getRecords())){
            for (AppImGroupJoinLogVo record : result.getRecords()) {
                record.setBeforeTime(getTimeAgo(record.getCreateTime()));
            }
        }
        return TableDataInfo.build(result);
    }

    public static String getTimeAgo(Date date) {
        if (date == null) {
            return "";
        }
        long diffMillis = System.currentTimeMillis() - date.getTime();
        long diffSeconds = diffMillis / 1000;
        long diffMinutes = diffSeconds / 60;
        long diffHours = diffMinutes / 60;
        long diffDays = diffHours / 24;
        long diffMonths = diffDays / 30; // 简单估算
        long diffYears = diffDays / 365;

        if (diffSeconds < 60) {
            return "刚刚";
        } else if (diffMinutes < 60) {
            return diffMinutes + "分钟前";
        } else if (diffHours < 24) {
            return diffHours + "小时前";
        } else if (diffDays < 30) {
            return diffDays + "天前";
        } else if (diffMonths < 12) {
            return diffMonths + "个月前";
        } else {
            return diffYears + "年前";
        }
    }


    /**
     * 查询群组进退记录列表
     */
    @Override
    public List<AppImGroupJoinLogVo> queryList(AppImGroupJoinLogBo bo) {
        LambdaQueryWrapper<AppImGroupJoinLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppImGroupJoinLog> buildQueryWrapper(AppImGroupJoinLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppImGroupJoinLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGroupId() != null, AppImGroupJoinLog::getGroupId, bo.getGroupId());
        lqw.eq(bo.getUserId() != null, AppImGroupJoinLog::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), AppImGroupJoinLog::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), AppImGroupJoinLog::getAvatar, bo.getAvatar());
        lqw.eq(bo.getActionType() != null, AppImGroupJoinLog::getActionType, bo.getActionType());
        lqw.eq(bo.getSourceUserId() != null, AppImGroupJoinLog::getSourceUserId, bo.getSourceUserId());
        lqw.like(StringUtils.isNotBlank(bo.getSourceNickname()), AppImGroupJoinLog::getSourceNickname, bo.getSourceNickname());
        return lqw;
    }

    /**
     * 新增群组进退记录
     */
    @Override
    public Boolean insertByBo(AppImGroupJoinLogBo bo) {
        AppImGroupJoinLog add = BeanUtil.toBean(bo, AppImGroupJoinLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改群组进退记录
     */
    @Override
    public Boolean updateByBo(AppImGroupJoinLogBo bo) {
        AppImGroupJoinLog update = BeanUtil.toBean(bo, AppImGroupJoinLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppImGroupJoinLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除群组进退记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean addList(List<AppImGroupJoinLogBo> bo) {
        List<AppImGroupJoinLog> list = BeanUtil.copyToList(bo, AppImGroupJoinLog.class);
        baseMapper.insertBatch(list);
        return true;
    }

    @Override
    public R<?> setGroupRemark(String groupId,String remark) {
        //查询加群记录
        LambdaQueryWrapper<AppImGroupJoinLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppImGroupJoinLog::getUserId, LoginHelper.getUserId());
        wrapper.eq(AppImGroupJoinLog::getGroupId, groupId);
        wrapper.eq(AppImGroupJoinLog::getActionType, 1);
        List<AppImGroupJoinLog> appImGroupJoinLogVos = baseMapper.selectList(wrapper);
        if (CollUtil.isNotEmpty(appImGroupJoinLogVos)){
            AppImGroupJoinLog last = CollUtil.getLast(appImGroupJoinLogVos);
            last.setRemark(remark);
            baseMapper.updateById(last);
            return R.ok();
        }
        return R.ok();
    }

    @Override
    public R<?> getGroupRemark(String groupId) {
        //查询加群记录
        LambdaQueryWrapper<AppImGroupJoinLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppImGroupJoinLog::getUserId, LoginHelper.getUserId());
        wrapper.eq(AppImGroupJoinLog::getGroupId, groupId);
        wrapper.eq(AppImGroupJoinLog::getActionType, 1);
        List<AppImGroupJoinLog> appImGroupJoinLogVos = baseMapper.selectList(wrapper);
        if (CollUtil.isNotEmpty(appImGroupJoinLogVos)){
            AppImGroupJoinLog last = CollUtil.getLast(appImGroupJoinLogVos);
            return R.ok("获取成功",last.getRemark());
        }
        return R.ok("群聊");
    }
}
